<?php

namespace App\Models\Traits;

use App\Models\Files;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Support\Facades\Auth;

/**
 * 多态方式关联多个上传文件。
 *
 * @property File[]|\Illuminate\Database\Eloquent\Collection $files 材料集合
 */
trait HasManyFiles
{
    public static function bootHasManyFiles()
    {
        static::deleted(function ($model) { /** @var static $model */
            //删除 model 的同时，删除关联的文件
            foreach ($model->files as $file) {
                $file->delete();
            }
        });
        static::saving(function ($model) {
            if($model->isDirty('is_push')){
                $model->files()->each(function ($file) use ($model) {
                    $file->is_push = $model->is_push;
                    $file->save();
                });
            }
        });
    }

    public function files(): MorphMany
    {
        return $this->morphMany(Files::class, 'ilk');
    }
}
